package com.longyi.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.longyi.entity.User;
import com.longyi.entity.UserVO;
import com.longyi.service.UserService;
import com.sun.javafx.binding.StringFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.logging.SimpleFormatter;
import java.util.stream.Stream;

/**
 * @author wuyanshen
 * @date 2020-02-10 6:20 下午
 * @discription 描述
 */
@Slf4j
@RestController
@RequestMapping("demo")
public class DemoController {

    @Autowired
    private UserService userService;

    @PostMapping("save")
    public String add(@RequestBody UserVO user){
        userService.add(user);
        return "success";
    }

    @PutMapping("update")
    public String update(@RequestBody User user){
        userService.updateById(user);
        return "success";
    }

    @GetMapping("page")
    public IPage<User> all(Page page, UserVO user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);

        if (user.getName()!=null){
            queryWrapper.lambda().like(User::getName,user.getName());
        }
        if (user.getUpdateTime()!=null){
            queryWrapper.lambda().eq(User::getUpdateTime,user.getUpdateTime());
//            queryWrapper.apply("date_format(update_time,'%Y-%m-%d %H:%i:%S')='"+df.format(user.getUpdateTime())+"'");
        }

        if (user.getBeginTime()!=null && user.getEndTime()!=null){
            queryWrapper.lambda().between(User::getUpdateTime,df.format(user.getBeginTime()),df.format(user.getEndTime()));
        }
        return userService.page(page,queryWrapper);
    }

    @GetMapping("all")
    public List<User> all(){
        return userService.list();
    }

    @DeleteMapping("delete/{id}")
    public String delete(@PathVariable("id") int id){
        userService.removeById(id);
        return "success";
    }

    @GetMapping("cookie")
    public void test(String cookieName, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        //当前时间
        String currentTime = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN).format(LocalDateTime.now());
        log.info("当前时间是：{}",currentTime);
        Cookie cookie1 = new Cookie("currentTime", URLEncoder.encode(currentTime,"UTF-8"));
//        cookie1.setMaxAge(10);
        response.addCookie(cookie1);
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            Optional<Cookie> name = Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(cookieName)).findFirst();
            String value = null;
            if (name.isPresent()){
                value = URLDecoder.decode(name.get().getValue(),"UTF-8");
                response.getWriter().write("您上次访问时间是："+value);
            }else{
                response.getWriter().write("您要找的cookie不存在");
            }
        }else {
            response.getWriter().write("您是第一次访问");
        }
    }

    @GetMapping("session")
    public void session(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(20);
        log.info("session的id是：{}",session.getId());
//        response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/json; charset=utf-8");
        String str = String.format("session的id是：%s",session.getId());
        User user = new User();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        session.setAttribute("user",json);
        response.getWriter().write(json);
    }

    @GetMapping("info")
    public void info(HttpSession session,HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        String json = null;
        if (session.getAttribute("user")!=null){
            json = (String)session.getAttribute("user");
            response.getWriter().write(json);
        }else {
            response.getWriter().write("session失效了");
        }
    }

    @GetMapping("index")
    public String index(Model model){
        model.addAttribute("lastRequestTime","我是默认值");
        return "index";
    }


}
